package com.mediacloud.app.newsmodule.service;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.Environment;
import android.os.IBinder;
import android.util.Log;

import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.HttpHandler;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.loopj.android.http.RequestParams;
import com.mediacloud.app.assembly.common.MD5Encoder;
import com.mediacloud.app.assembly.interfaces.LoadNetworkBack;
import com.mediacloud.app.cloud.ijkplayersdk.obj.MediaVideoItem;
import com.mediacloud.app.newsmodule.drama.DramaVideoHelper;
import com.mediacloud.app.newsmodule.model.DownLoad;
import com.mediacloud.app.newsmodule.model.OnDownloadProcessListener;
import com.mediacloud.app.newsmodule.utils.DownloadDB;
import com.mediacloud.app.reslib.util.DataInvokeUtil;
import com.mediacloud.app.reslib.util.HTTPClient;
import com.mediacloud.app.reslib.util.RequestParamsX;
import java.io.File;
import java.util.ArrayList;

public class DownloadService extends Service {

    ArrayList<DownLoad> mQueue = new ArrayList<DownLoad>();
    DownloadDB mDownloadDB;
    OnDownloadProcessListener mOnDownloadProcessListener;

    public void setOnDownloadProcessListener(OnDownloadProcessListener listener) {

        mOnDownloadProcessListener = listener;
    }

    public DownloadService() {
    }

    private Binder serviceBinder = new DownLoadServiceBinder();

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        return serviceBinder;
    }

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        mDownloadDB = new DownloadDB(getApplicationContext());
        ArrayList<DownLoad> data = mDownloadDB.getDownLoadData(DownloadDB.ING_TABLE_NAME_);
        if (data != null) {
            mQueue.addAll(data);
        }
        toDownLoad();
        return super.onStartCommand(intent, flags, startId);
    }

    public void toDownLoad() {
        if (mQueue.size() > 0) {
            if (mQueue.get(0).getTypes().equals("0")) {
                getViedeoInfo(mQueue.get(0).getUrl(), mQueue.get(0).getTagId());

            } else {
                dowloadQueue(mQueue.get(0));
            }
        }
    }

    private void getViedeoInfo(String article_id, String catalog_id) {
        String interfaces = "api/content/drama-info";
        RequestParams param = new RequestParamsX();
        param.put("article_id", article_id);
        param.put("catalog_id", catalog_id);

//        param.put("api_version", "1.2.3");
        HTTPClient helper = new HTTPClient();
        helper.getNetData(new LoadNetworkBack<DramaVideoHelper>() {

            @Override
            public void Success(DramaVideoHelper result) {




                if (result.mUrls == null) {
                    return;
                }
                //Log.i("test", "result.mUrls.mp4Address.size():" + result.mUrls.mp4Address.size());
                if (result.mUrls.mp4Address.size() != 0) {

                    int rate = Integer.parseInt(mQueue.get(0).getRate());
                    if (result.mUrls.mp4Address.size() > (rate + 1)) {
                        mQueue.get(0).setUrl(result.mUrls.mp4Address.get(rate).url);
                        mQueue.get(0).setTypes("1");
                        dowloadQueue(mQueue.get(0));
                    } else {
                        mQueue.get(0).setUrl(result.mUrls.mp4Address.get(result.mUrls.mp4Address.size()).url);
                        mQueue.get(0).setTypes("1");
                        dowloadQueue(mQueue.get(0));
                    }
                } else {
                    mQueue.get(0).setTagId("-1");
                    mDownloadDB.deleteData(mQueue.get(0), DownloadDB.ING_TABLE_NAME_);
                    mDownloadDB.saveData(mQueue.get(0), DownloadDB.Complete_TABLE_NAME_);
                    mQueue.remove(0);
                }
            }

            @Override
            public void Failure(Object obj) {

            }

            @Override
            public void otherData(String result) {

            }
        }, DataInvokeUtil.ServerURL + interfaces, new DramaVideoHelper(), param);
    }

    public void addQueue(DownLoad item) {
        mDownloadDB.saveData(item, DownloadDB.ING_TABLE_NAME_);
        mQueue.add(item);

        if (mQueue.size() == 1) {
            toDownLoad();
        }


    }

    public void addQueues(ArrayList<DownLoad> datas) {
        for (int i = 0; i < datas.size(); i++) {
            mDownloadDB.saveData(datas.get(i), DownloadDB.ING_TABLE_NAME_);
        }
        mQueue.addAll(datas);
        if (mQueue.size() == 1) {
            toDownLoad();
        }
    }

    private HttpHandler handler;

    private void dowloadQueue(DownLoad item) {

        HttpUtils http = new HttpUtils();
        String sdPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/appfactory/videocach/" + MD5Encoder.encode(item.getUrl()) + ".mp4";
        handler = http.download(item.getUrl(), sdPath, true, false, new RequestCallBack<File>() {

            @Override
            public void onStart() {
                // TODO Auto-generated method stub
                super.onStart();
            }

            @Override
            public void onLoading(long total, long current, boolean isUploading) {
                // TODO Auto-generated method stub
                super.onLoading(total, current, isUploading);
                if (mOnDownloadProcessListener != null) {
                    mOnDownloadProcessListener.onProcess(mQueue.get(0).getId(), total, current, null);
                }
            }

            @Override
            public void onSuccess(ResponseInfo<File> arg0) {
                // TODO Auto-generated method stub
               mDownloadDB.deleteData(mQueue.get(0),DownloadDB.ING_TABLE_NAME_);
                mDownloadDB.saveData(mQueue.get(0), DownloadDB.Complete_TABLE_NAME_);
                mQueue.remove(0);
                toDownLoad();
            }

            @Override
            public void onFailure(HttpException arg0, String arg1) {
                // TODO Auto-generated method stub
                mQueue.get(0).setTagId("-2");
                mDownloadDB.deleteData(mQueue.get(0), DownloadDB.ING_TABLE_NAME_);
                mDownloadDB.saveData(mQueue.get(0), DownloadDB.Complete_TABLE_NAME_);
                mQueue.remove(0);
                toDownLoad();

            }
        });
    }

    public class DownLoadServiceBinder extends Binder
    {
        public DownloadService getService() {
            return DownloadService.this;
        }
    }
}